var express = require('express')
var crypto = require('./crypto')
var app = express()
var path = require('path')
var fs = require('fs')
var multiparty = require('multiparty')
app.use('/css', express.static('./public/css'))
app.use('/js', express.static('./public/js'))
app.use('/img', express.static('./public/img'))
app.use('/fonts', express.static('./public/fonts'))
app.all('*', function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
  res.header("Access-Control-Allow-Headers", "token,name,age,Origin, X-Requested-With, Content-Type, Accept, Authorization");
  res.header('X-Powered-By', '123')
  res.header('Access-Control-Expose-Headers', 'setcookie,X-Powered-By')
  next();
});
app.use('/upla', (req, res) => { // 接收文件上传
  let form = new multiparty.Form({
    uploadDir: './public/merge' //指定上传的文件路径
  });
  let imgName = req.query.name
  let size = req.query.size
  form.parse(req, (err, field, files) => {
    files && files.file.map(x => { // 必须这样写
      let img = imgName || x.originalFilename
      fs.rename(x.path, './public/merge/' + img, () => {
        if (size === imgName) {
          res.json({ok:200})
        } else {
          res.end(JSON.stringify({
            ok: 304
          }))
        }
      })
    })
    // res.end(JSON.stringify({
    //   ok: 200
    // }))
  })
  form.on('field', (name, value) => {
    // name:字段名
    // value:值
    console.log('数据:', name, value);

  })
  //接收文件数据
  form.on('file', (name, file) => {
    console.log('文件:', name, file);
  })
  //表单解析完成
  form.on('close', () => {
    console.log('完成');
  })
})
app.get('/merge', (req, res) => {
  let filePath = './public/img/' + req.query.name
  fs.readdir('./public/merge', (err, list) => {
    console.log(list)
    list.map(res => {
      fs.appendFileSync(filePath, fs.readFileSync('./public/merge/' + res));
      fs.unlinkSync('./public/merge/' + res)
    })
    res.json({
      url: `http://localhost:4000/img/${req.query.name}`
    })
  })
})
app.post('/data', (req, res) => {
  res.json({
    ok: 200
  })
})
app.use('/index', (req, res) => {
  res.sendFile('E:/vue-cli3.0/vue/dist/index.html')
})
app.use('/info', (req, res) => {
  res.redirect('/index')
})
app.use('/demo', (req, res) => {
  res.json({
    ok: 200
  })
})
app.use('/bgs', async (req, res) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("content-type", "image/png; charset=utf-8");

  function read() {
    return new Promise((resolve, rejects) => {
      fs.readFile('./public/img/2020.jpg', function (err, data) {
        resolve(data)
        rejects(err)
      })
    })
  }
  let data = await read()
  console.log(data)
  res.send(data)
})
app.use('/html', (req, res) => {
  var cry = crypto.aesEncrypt('1212', '123')
  res.header('setcookie', cry)
  console.log(crypto.aesDecrypt(cry, '123'))
  res.json({
    ok: 200
  })
})


app.listen(4000, () => {
  console.log('服务开启')
})